package com.scau.dao.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.shiro.session.mgt.SessionFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.scau.dao.BaseDao;
import com.scau.dao.IAdminDao;
import com.scau.vo.Admin;
import com.scau.util.DateTransform;

/**
 * @author Jinglun
 * @create 2017年3月12日
 */
public class AdminDaoImpl extends BaseDao implements IAdminDao {

	private Session session = null;
	private Transaction tx = null;
	private String hql = "";
	
	// 注册
	@Override
	public boolean register(Admin admin) {
		session = getSession();
		tx = session.beginTransaction();
		hql = "from Admin admin where admin.adminName = '"
				+ admin.getName() + "'";

		// 当确定返回的实例只有一个或者null时，用uniqueResult方法
		Admin isAdminExist = (Admin) session.createQuery(hql).uniqueResult();

		if (isAdminExist != null) {
			System.out.println("管理员：" + admin.getName() + "已经存在，不能重复注册！");
			return false;
		} else {
			// 默认设置type为0，创建时间为当前时间
			Date date = new Date();
			DateTransform dt = new DateTransform();
			Timestamp ts = dt.dToTimestamp(date);
			
			admin.setGmtCreate(ts);
			System.out.println("createTime为："+admin.getGmtCreate());
			admin.setType(0);
			System.out.println("adminType为："+admin.getType());
			
			session.save(admin); //将用户保存
			tx.commit(); // 事务关闭，数据才真正插入数据库
			session.close();
			System.out.println("管理员：" + admin.getName() + "添加成功！");
			return true;
		}

	}
	
	// 登录
	@Override
//	public boolean login(Admin admin) {
//		session = getSession();
//		tx = session.beginTransaction();
//		hql = "from Admin admin where admin.adminName = '" + admin.getName()
//				+"' and admin.adminPassword = '" + admin.getPassword()+"'";
//		
//		Query query = session.createQuery(hql);
//		List list = query.list();
//		// 迭代器
//		Iterator it = list.iterator();
//		
//		if(it.hasNext()){
//			System.out.println("用户：" + admin.getName() + "账号密码正确！");
//			// 提交事务
//			tx.commit();
//			session.close();
//			return true;
//		}
//		else {
//			System.out.println("用户：" + admin.getName() + "账号密码错误！");
//			return false;
//		}
//	}
	
	// 查询所有管理员
	public List<Admin> listAdmin(){
		session = getSession();
		hql = "from Admin ad";
		Query query = session.createQuery(hql);
		List<Admin> listAd = query.list();
		session.close();
		return listAd;
	}
	
	// 根据姓名查找管理员
	public List<Admin> findByName(String name){
		session = getSession();
		
		hql = "from Admin a where a.name = '" + name +"'";
		Query query = session.createQuery(hql);
		List<Admin> foundAdmin = query.list();
		
		System.out.println("dao里查出来的foundAdmin:" + foundAdmin);
	
		session.close();
		return foundAdmin;
	}

}
